#include "shader/sunShader.h"
#include "helper.h"

bool SunShader::is_built = false;
GLuint SunShader::ID;

SunShader::SunShader()
{
    if(!is_built) {
		ID = load_shader("../shader/colorShader.vert", "../shader/colorShader.frag");
		is_built = true;
	}
    set_tempreture(3000);
}
// 设置开尔文温度
void SunShader::set_tempreture(float t) {
    // 引用https://blog.csdn.net/lz0499/article/details/104088393
    t = t/ 100;
    // red
    if(t <= 66) {
        color.r = 255;
    } else {
        color.r = t - 60;
        color.r = 329.698727446 * glm::pow(color.r, -0.1332047592);
        color.r = color.r < 0 ? 0 : color.r;
        color.r = color.r > 255 ? 255 : color.r;
    }
    // green
    if(t <= 66) {
        color.g = t;
        color.g = 99.4708025861 * glm::log(color.g) - 161.1195681661;
        color.g = color.g < 0 ? 0 : color.g;
        color.g = color.g > 255 ? 255 : color.g;
    } else {
        color.g = t - 60;
        color.g = 288.1221695283 * glm::pow(color.g, -0.0755148492);
        color.g = color.g < 0 ? 0 : color.g;
        color.g = color.g > 255 ? 255 : color.g;
    }
    // blue
    if(t >= 66) {
        color.b = 255;
    } else {
        color.b = t - 10;
        color.b = 138.5177312231 * glm::log(color.b) - 305.0447927307;
        color.b = color.b < 0 ? 0 : color.b;
        color.b = color.b > 255 ? 255 : color.b;
    }
    color /= 255;
}

void SunShader::render(Mesh &mesh, glm::mat4 &modelMat, glm::mat4 &viewMat, glm::mat4 &projMat) const {
    glUseProgram(ID);
	glUniformMatrix4fv(glGetUniformLocation(ID, "model"), 1, GL_FALSE, glm::value_ptr(modelMat));
	glUniformMatrix4fv(glGetUniformLocation(ID, "view"), 1, GL_FALSE, glm::value_ptr(viewMat));
	glUniformMatrix4fv(glGetUniformLocation(ID, "proj"), 1, GL_FALSE, glm::value_ptr(projMat));
    glUniform3fv(glGetUniformLocation(ID, "color"), 1, glm::value_ptr(color));
    //增加纹理
	glActiveTexture(GL_TEXTURE0);
	glBindTexture(GL_TEXTURE_2D, texture_id);
	glUniform1i(glGetUniformLocation(ID, "texture"), 0);
	glBindVertexArray(mesh.get_VAO());
	glDrawElements(GL_TRIANGLES, mesh.indices.size(), GL_UNSIGNED_INT, 0);
}